float4x4 World;
float4x4 View;
float4x4 Projection;

float4 Color;
float4 CameraPos;

int2 Start;
int2 Dimensions;

int LOD;

float Morph;

// Following code by Fillip Strugar, uber the Zlib license.
const float2 g_gridDim = float2( 10, 10 );
//const float2 g_quadScale = float2( 1, 1 );

float2 morphVertex( float2 gridPos, float2 vertex, float morphK, float2 g_quadScale)
{
    float2 fracPart = frac( gridPos.xy * g_gridDim.xy * 0.5 ) * 2.0 / g_gridDim.xy;
    return vertex.xy - fracPart * g_quadScale.xy * morphK;
} 

//End block

Texture Heightmap;
sampler HeightmapSampler = sampler_state {
    Texture = <Heightmap>;
    MinFilter = POINT;
    MagFilter = POINT;
    MipFilter = POINT;
};

Texture GroundTexture;
sampler ColorSampler = sampler_state {
    Texture = <GroundTexture>;
    MinFilter = LINEAR;
    MagFilter = LINEAR;
    MipFilter = LINEAR;
};

// TODO: add effect parameters here.

struct VertexShaderInput
{
    float4 Position : POSITION0;
	float2 UV : TEXCOORD0;
};

struct VertexShaderOutput
{
    float4 Position : POSITION0;
	float2 UV : TEXCOORD0;
	float4 WorldPosition : TEXCOORD1;
};
VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
{
    VertexShaderOutput output;


	float4 scalar = float4(Dimensions.x/1024.0f,0,Dimensions.y/1024.0f,1);
	float4 offset = float4(Start.x/1024.0f, 0, Start.y/1024.0f, 1);
	
	output.WorldPosition = input.Position * scalar + offset;
	float4 sample = tex2Dlod(HeightmapSampler, float4(output.WorldPosition.xz,0, 0));
	float height = (sample.g *256 + sample.r);
	float4 innerPosition = float4(input.Position.x, 
							height, 
							input.Position.z, input.Position.w);
	
    float4 worldPosition = mul(innerPosition, World);
	if ((input.Position.x * 10)%2 == 1 || (input.Position.z * 10)%2 == 1)
	{
		worldPosition.xz = morphVertex(input.Position.xz, worldPosition.xz, Morph, Dimensions);
		output.WorldPosition.xz = morphVertex(input.Position.xz, output.WorldPosition.xz, Morph, scalar.xz);
		sample = tex2Dlod(HeightmapSampler, float4(output.WorldPosition.xz,0,0));
		height = (sample.g *256 + sample.r);
		worldPosition.y = height;

	}
    float4 viewPosition = mul(worldPosition, View);
    output.Position = mul(viewPosition, Projection);
	output.UV = input.UV;
    
    return output;
}

float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
    return float4(tex2D(HeightmapSampler, float2(input.WorldPosition.x, input.WorldPosition.z)).r,0,0,1);//float4(input.UV,0,0);//Color;
}

technique Technique1
{
    pass Pass1
    {
        // TODO: set renderstates here.

        VertexShader = compile vs_3_0 VertexShaderFunction();
        PixelShader = compile ps_3_0 PixelShaderFunction();
    }
}
